<?php

namespace App\Service\Wechat;

use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use App\Service\IService;
use Common\Common;
use EasyWeChat\OfficialAccount\Application;

class MpService extends IService
{
    public function getRedirectUrl(array $data): array
    {
        $app = self::app();
        $oauth = $app->getOAuth();
        $redirectUrl = $oauth->scopes([$data['scope'] ?? 'snsapi_base'])
            ->redirect($app->getConfig()->get('oauth.redirect_url') . '/api/wechat/mp/redirectTo?r=' . $data['to_url']);
        return ['url' => $redirectUrl];
    }

    public function login(array $param): array
    {
        $app = self::app();
        $client = $app->getClient();

        $res = $client->get('/sns/oauth2/access_token', [
            'query' => [
                'grant_type' => 'authorization_code',
                'code' => $param['code'],
                'appid' => $app->getConfig()->get('app_id'),
                'secret' => $app->getConfig()->get('secret'),
            ]
        ]);
        $data = $res->toArray();
        if (empty($data['openid'])) throw new BusinessException(ResultCode::NOT_FOUND, '未获取到用户信息');
        if ($data['scope'] == 'snsapi_base') {
            return ['openid' => $data['openid']];
        }
        $res = file_get_contents('https://api.weixin.qq.com/sns/userinfo?' . http_build_query([
                'access_token' => $data['access_token'],
                'openid' => $data['openid'],
                'lang' => 'zh_CN',
            ]));
        $res = json_decode($res, true);
        return ['openid' => $res['openid'], 'avatar' => $res['headimgurl'], 'name' => $res['nickname']];
    }

    public static function app(): Application
    {
        $config = Common::getConfigByGroup('wechat');
        $config = [
            'app_id' => $config['mp_app_id']['value'],
            'secret' => $config['mp_app_secret']['value'],
            'aes_key' => $config['mp_aes_key']['value'] ?? '',
            'token' => $config['mp_token']['value'] ?? '',
            'oauth' => [
                'redirect_url' => $config['mp_app_domain']['value'],
            ],
            'http' => [
                'throw' => true,
                'timeout' => 5.0,
                'retry' => true,
            ],
        ];
        $app = new Application($config);
        $app->setCache(Common::container()->get(\Psr\SimpleCache\CacheInterface::class));
        return $app;
    }

    public static function sendTplMsg(string $tpl, string $openid, array $data, array $ext = []): array
    {
        /*$ext = [
            'client_msg_id'=>'',
            'url'=>'',
            'miniprogram' => [
                'appid' => '',
                'pagepath' => '',
            ],
        ]*/
        return static::app()->getClient()->postJson('/cgi-bin/message/template/send', array_merge([
            'touser' => $openid,
            'template_id' => $tpl,
            'data' => $data,
        ], $ext))->toArray();
    }

    public function tplList(): array
    {
        return static::app()->getClient()->get('/cgi-bin/template/get_all_private_template')->toArray();
    }
}